//bijgewerkt
#include <p24FJ32GA002.h>
#include <stdio.h>
/* Timer1, PWM
 * Timer2, Delay
 * Timer3, ADC
 * Timer4, Follow UP
 */



// TIMER 2 -----------------------------------------

void InitTimer2(void) 
{
  T2CONbits.TCKPS = 0x1;	// GEEN PRESCALER
  T2CONbits.TCS	= 0;		// SYSTEM CLOCK SOURCE
  PR2	= 0xFFFF;
}

// Delay die een timer als counter gebruikt.
// Alternatief zou een for loop kunnen zijn, maar dit is beter
void Delay(int Count)
{
  // Count mag niet NULL zijn, dan standaard waarde van FFF
  Count = (Count > 0 ? Count : 1000);

  T2CONbits.TON	= 1;		// TIMER AANZETTEN
  while ( !(TMR2 == Count) );	// HEEFT TIMER WAARDE BEREIKT?
  T2CONbits.TON	= 0;		// TIMER UITZETTEN
  TMR2	= 0;				// TIMER LEGEN
}


// Sampling Control
#define Fosc		8000000
#define Fcy			(Fosc/2)
#define Fs   		400
#define SAMPPRD		(Fcy/Fs)-1

/*====================================================================
Timer 3 is setup to time-out every 250 microseconds (4Khz Rate). 
As a result, the module will stop sampling and trigger a conversion on
 every Timer3 time-out, i.e., Ts=250us. At that time, the conversion
 process starts and completes Tc=14*Tad periods later.

When the conversion completes, the module starts sampling again. 
However, since Timer3 is already on and counting, about (Ts-Tc)us
 later, Timer3 will expire again and trigger next conversion. 
====================================================================*/
void InitTimer3(void) 
{
    TMR3 = 0x0000;
    PR3 = SAMPPRD;
    IFS0bits.T3IF = 0;
    IEC0bits.T3IE = 0;

    //Start Timer 3
    T3CONbits.TON = 1;
}


// TIMER 4 -----------------------------------------
void InitTimer4(void) 
{
  T4CONbits.TCKPS 	= 0xFF;		// GEEN PRESCALER
  T4CONbits.TCS		= 0;		// SYSTEM CLOCK SOURCE
  IEC1bits.T4IE		= 1;		// INTERRUPT ENABLE VOOR TMR4
  IFS1bits.T4IF 	= 0;		// CLEAR INTERRUPT
  IPC6bits.T4IP 	= 2;		// CLEAR INTERRUPT
  PR4				= 0xFFFF;	
}

void StartTimer4(void) 
{
  T4CONbits.TON	= 1; // start timer
}

void StopTimer4(void) 
{
  T4CONbits.TON	= 0; // start timer
}

void TickTimer4(void)
{
  TMR4 = 0xA000;
}

void _ISR _T4Interrupt(void)
{
  TMR4	= 0;
  CheckDiff();
  IFS1bits.T4IF 	= 0;		// CLEAR INTERRUPT		
}
